package com.ruoyi.basebill.controller;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basebill.domain.WfzNzjjt;
import com.ruoyi.basebill.domain.WfzWebservice;
import com.ruoyi.basebill.service.IWfzWebserviceService;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.webServiceUtil.WSWfzHrztFacadeSrvProxy;
import com.ruoyi.webServiceUtil.WSWfzHrztFacadeSrvProxyServiceLocator;
import com.ruoyi.webServiceUtil.WebServiceHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.axis.client.Stub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basebill.domain.WfzNzjch;
import com.ruoyi.basebill.service.IWfzNzjchService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 冲回年终奖Controller
 * 
 * @author xiefeng
 * @date 2022-12-13
 */
@Api("年终奖冲回")
@RestController
@RequestMapping("/basebill/nzjch")
public class WfzNzjchController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    @Autowired
    private IWfzNzjchService wfzNzjchService;

    @Autowired
    private IWfzWebserviceService wfzWebserviceService;

    /**
     * 查询冲回年终奖列表
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:list')")
    @GetMapping("/list")
    public TableDataInfo list(WfzNzjch wfzNzjch)
    {
        startPage();
        List<WfzNzjch> list = wfzNzjchService.selectWfzNzjchList(wfzNzjch);
        return getDataTable(list);
    }

    /**
     * 导出冲回年终奖列表
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:export')")
    @Log(title = "冲回年终奖", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WfzNzjch wfzNzjch)
    {
        List<WfzNzjch> list = wfzNzjchService.selectWfzNzjchList(wfzNzjch);
        ExcelUtil<WfzNzjch> util = new ExcelUtil<WfzNzjch>(WfzNzjch.class);
        util.exportExcel(response, list, "冲回年终奖数据");
    }

    /**
     * 获取冲回年终奖详细信息
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:query')")
    @GetMapping(value = "/{fid}")
    public AjaxResult getInfo(@PathVariable("fid") Long fid)
    {
        return success(wfzNzjchService.selectWfzNzjchByFid(fid));
    }

    /**
     * 新增冲回年终奖
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:add')")
    @Log(title = "冲回年终奖", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WfzNzjch wfzNzjch)
    {
        wfzNzjch.setFcreator(getUsername());
        wfzNzjch.setFlastupdateuser(getUsername());
        return toAjax(wfzNzjchService.insertWfzNzjch(wfzNzjch));
    }

    /**
     * 修改冲回年终奖
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:edit')")
    @Log(title = "冲回年终奖", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WfzNzjch wfzNzjch)
    {
        wfzNzjch.setFlastupdateuser(getUsername());
        wfzNzjch.setFlastupdatetime(new Date());
        return toAjax(wfzNzjchService.updateWfzNzjch(wfzNzjch));
    }

    /**
     * 删除冲回年终奖
     */
    @PreAuthorize("@ss.hasPermi('basebill:nzjch:remove')")
    @Log(title = "冲回年终奖", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fids}")
    public AjaxResult remove(@PathVariable Long[] fids)
    {
        return toAjax(wfzNzjchService.deleteWfzNzjchByFids(fids));
    }

    /**
     * 调用webService接口
     */
    @ApiOperation("EAS接口调用")
    @GetMapping(value = "importNzjch/{fids}")
    public AjaxResult importNzjch(@PathVariable Long[] fids){

        StringBuffer buffer = new StringBuffer();
        //准备两个参数：分别用来记录成功的调用条数，和失败的调用条数
        int succNum = 0;
        int failNum = 0;
        WfzWebservice wfzWebservice = new WfzWebservice();
        wfzWebservice.setJknumber("EAS001");
        List<WfzWebservice> wfzWebservices = wfzWebserviceService.selectWfzWebserviceList(wfzWebservice);

        wfzWebservice = wfzWebservices.get(0);

        String jkpassword = wfzWebservice.getJkpassword(); //密码
        String jkinurl = wfzWebservice.getJkinurl(); //业务接口
        String dcname = wfzWebservice.getDcname(); //数据中心名称
        String jkurl = wfzWebservice.getJkurl(); //登录接口
        String jkmethod = wfzWebservice.getJkmethod(); //业务方法
        String jkusername = wfzWebservice.getJkusername(); //接口用户


        for(int i =0;i<fids.length;i++){
            long fid = fids[i];

            //获取冲回年终奖的详细信息
            WfzNzjch wfzNzjch = wfzNzjchService.selectWfzNzjchByFid(fid);
            String json = wfzNzjchService.importNzjch(wfzNzjch);
            log.info("冲回年终奖同步eas："+json);
            try {
                String login = WebServiceHelper.login(jkusername, jkpassword, jkurl, dcname);
//                String result = WebServiceHelper.serviceInterface(login, jkinurl, jkmethod, json, "WFZ002");
                URL url = new URL(jkinurl);
                WSWfzHrztFacadeSrvProxy wsWfzHrztFacade = new WSWfzHrztFacadeSrvProxyServiceLocator().getWSWfzHrztFacade(url);
                ((Stub) wsWfzHrztFacade).setHeader("http://login.webservice.bos.kingdee.com","SessionId",login);
                String result = wsWfzHrztFacade.insertBill("WFZ015", json);
                log.info("冲回年终奖同步eas结果："+result);
                JSONObject reInfo = JSONObject.parseObject(result);
                String fState = reInfo.getString("FState");
                if ("1".equals(fState)){
                    //记录日志后续开发
                    wfzNzjch.setFiseas((long)1);
                    wfzNzjchService.updateWfzNzjch(wfzNzjch);
                    //将成功信息记录下来
                    succNum++;
                    buffer.append("<br/>" + succNum + "、数据 ID " + wfzNzjch.getFid() + " 导入成功");
                }else {
                    //记录日志后续开发
//                    buffer.append(reInfo.getString("FMessage"));
                    failNum++;
                    buffer.append("<br/>" + failNum + "、数据 ID " + wfzNzjch.getFid() + " 导入失败"+reInfo.getString("Fmessage"));

                }
            } catch (ServiceException e) {
                throw new RuntimeException(e);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            System.out.println(json);
        }

        if (failNum > 0){
            buffer.insert(0,"很抱歉，调用失败！共"+ failNum + "条数据调用失败，错误如下：");
        }else {
            buffer.insert(0,"所有的数据全部调用成功！共 "+succNum +" 条，数据如下：");
        }
        return AjaxResult.success(buffer.toString());
    }
}
